package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.internal.Notification;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.SearchBar;

import java.util.concurrent.Callable;

final class SearchBarFoldOnSubscribe extends Observable<Object> {
    final SearchBar view;
    final Callable<Boolean> handled;

    SearchBarFoldOnSubscribe(SearchBar view, Callable<Boolean> handled) {
        this.view = view;
        this.handled = handled;
    }

    @Override
    protected void subscribeActual(final Observer<? super Object> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer, handled);
        observer.onSubscribe(listener);
        view.setFoldListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements SearchBar.FoldListener {
        final SearchBar view;
        final Observer<? super Object> observer;
        private final Callable<Boolean> handled;

        Listener(SearchBar view, Observer<? super Object> observer, Callable<Boolean> handled) {
            this.view = view;
            this.observer = observer;
            this.handled = handled;
        }

        @Override
        protected void onDispose() {
            view.setQueryListener(null);
        }

        @Override
        public boolean onFold() {
            if (!isDisposed()) {
                try {
                    if (handled.call()) {
                        observer.onNext(Notification.INSTANCE);
                        return true;
                    }
                } catch (Throwable e) {
                    observer.onError(e);
                    dispose();
                }
            }
            return false;
        }
    }
}
